package com.ytjj.qmyx.mall.service.impl.gcyp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.model.AdapayCommon;
import com.huifu.adapay.model.Payment;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.constants.AdapayConstants;
import com.ytjj.qmyx.mall.model.dto.AdapayH5MiniPayDto;
import com.ytjj.qmyx.mall.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * H5 Adapay支付
 *
 */
@Service("H5-ADAPAY-MINI")
@Slf4j
@EnableConfigurationProperties(AdapayConstants.class)
public class AdapayMiniH5ApiServiceImpl implements WxService<AdapayH5MiniPayDto> {

    @Resource
    private AdapayConstants adapayConstants;
    @Autowired
    private CopyWriterConfigUtil copyWriterConfigUtil;

    /**
     * H5 发起 Adapay 的微信小程序预支付
     * @param adapayH5MiniPayDto
     * @return Map<String,String>
     */
    @Override
    public Map<String, String> doUnifiedOrder(AdapayH5MiniPayDto adapayH5MiniPayDto) throws Exception {
         try {
             String tradeNo = adapayH5MiniPayDto.getTradeNo();
             String realTotalMoney = adapayH5MiniPayDto.getRealTotalMoney();
             String productName = adapayH5MiniPayDto.getProductName();
             String goodsDesc = adapayH5MiniPayDto.getGoodsDesc();
             Integer payId = adapayH5MiniPayDto.getPayId();
             Integer orderId = adapayH5MiniPayDto.getOrderId();

             Map<String, Object> params = new HashMap<String, Object>();
             //order_no：创建收银台对象时上送的请求订单号，只能为英文、数字或者下划线的一种或多种组合
             params.put("order_no",tradeNo);
             //固定值:wxpay.createOrder
             params.put("adapay_func_code", "wxpay.createOrder");
             params.put("pay_amt", new BigDecimal(realTotalMoney).setScale(2,RoundingMode.CEILING));
             params.put("app_id", adapayConstants.getAPPID());
             //货币代码 cny：人民币
             params.put("currency",  "cny");
             //商品标题
             params.put("goods_title",  productName);
             //商品描述信息
             params.put("goods_desc", StringUtils.isEmpty(goodsDesc) ? productName : goodsDesc);
             //第三方已废除'callback_url'字符段
//             params.put("callback_url",  "");
             params.put("notify_url",  adapayConstants.getNOTIFY_URL());
             List<Map<String,Object>> list = new ArrayList<>();
             Map<String,Object> divMembers = new HashMap<>();
             divMembers.put("amount",new BigDecimal(realTotalMoney).setScale(2,RoundingMode.CEILING));
             divMembers.put("fee_flag","Y");
             divMembers.put("member_id","0");
             list.add(divMembers);
             params.put("div_members", Arrays.asList(divMembers));
             Map<String, Object> response = AdapayCommon.requestAdapayUits(params);
             Map<String,String> msgMap = JSONObject.parseObject(JSON.toJSONString(response), Map.class);
             return msgMap;
         } catch (Exception e) {
             String error =  String.format("=====支付订单:%s支付错误：%s====",adapayH5MiniPayDto.getTradeNo(),e.getMessage());
             FeiShuUtil.sendMsg(error);
             log.error(error);
             e.printStackTrace();
             throw new Exception(error);
         }
    }

    @Override
    public Map<String, String> doUnifiedRechargeOrder(AdapayH5MiniPayDto adapayH5MiniPayDto) throws Exception {
        return null;
    }

    /**
     * 查询Adapay h5小程序订单是否支付
     * @param tradeNo 支付订单
     * @return Map<String,String>
     */
    @Override
    public Map<String, String> wxOrderQuery(String tradeNo) throws Exception {
        Map<String,String> map = new HashMap<>();
        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id",adapayConstants.getAPPID());
        paymentParams.put("page_index", "1");
        paymentParams.put("page_size", "10");
        paymentParams.put("order_no",tradeNo);
//        paymentParams.put("created_gte", "1571466657929");
//        paymentParams.put("created_lte", "1571898657929");
        Map<String, Object> paymentList = Payment.queryList(paymentParams);
        try {
            if (null != paymentList) {
                log.info("===>h5的adapay微信小程序订单列表查询结果：{}", JSONObject.toJSONString(paymentList));
                Map<String,String> msgMap = JSONObject.parseObject(JSON.toJSONString(paymentList), Map.class);
                String response = msgMap.get("status");
                //转换成策略模式统一结构
                if ("succeeded".equals(response)) {
                    map.put("return_code","SUCCESS");
                    map.put("trade_state","SUCCESS");
                } else if ("pending".equals(response)) {
                    map.put("trade_state","USERPAYING");
                }
            }
        } catch (Exception e) {
            log.error("==========》调Adapay微信小程序查询支付状态出错e:{}", e);
        }
        return map;
    }

    @Override
    public Map<String, String> wxPhoneChargesQuery(String resOrderNo) throws Exception {
        return null;
    }

    @Override
    public Map refundOrders(String outTradeNo, String outRefundNo, Integer totalFee, Integer refundFee, String refundDesc) throws Exception {
        return null;
    }

    @Override
    public Map refundRecharge(String outTradeNo, String outRefundNo, Integer totalFee, Integer refundFee, String refundDesc) throws Exception {
        return null;
    }
}
